package com.github.xuemingyu.springboot.acticitycloud.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bidanet.bdcms.core.common.JsonParseTool;
import com.bidanet.bdcms.core.vo.Page;
import com.bidanet.hibernate.lambda.core.LambdaCriteria;
import com.dingtalk.api.response.OapiChatUpdateResponse;
import com.dingtalk.api.response.OapiUserGetResponse;
import com.github.xuemingyu.springboot.acticitycloud.dao.*;
import com.github.xuemingyu.springboot.acticitycloud.driver.dingtalk.DingTalkService;
import com.github.xuemingyu.springboot.acticitycloud.entity.*;
import com.github.xuemingyu.springboot.acticitycloud.service.ActivityService;
import com.github.xuemingyu.springboot.acticitycloud.service.SakuraEntryFormService;
import com.github.xuemingyu.springboot.acticitycloud.service.UserInfoService;
import com.google.common.base.Strings;
import com.taobao.api.ApiException;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: xmy
 * \* Date: 2019/1/28
 * \* Time: 10:26
 * \
 */
@Service
@Transactional
public class SakuraEntryFormServiceImpl extends BaseServiceImpl<SakuraEntryForm> implements SakuraEntryFormService {
    @Autowired
    private SakuraEntryFormDao sakuraEntryFormDao;
    @Autowired
    private DingTalkService dingTalkService;
    @Autowired
    private ActivityDao activityDao;
    @Autowired
    private ConversationDao conversationDao;
    @Autowired
    private UserInfoService userInfoService;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Autowired
    private SignRecordDao signRecordDao;
    SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public void queryLike(SakuraEntryForm sakuraEntryForm, Page<SakuraEntryForm> page) {
        LambdaCriteria<SakuraEntryForm> lambdaCriteria = lambdaQuery.create(SakuraEntryForm.class);
        if (StringUtils.isNotEmpty(sakuraEntryForm.getName())) {
            lambdaCriteria.like(q -> {
                q.setName(sakuraEntryForm.getName());
            });
        }
        if (Objects.nonNull(sakuraEntryForm.getActivityId())) {
            lambdaCriteria.eq(q -> {
                q.setActivityId(sakuraEntryForm.getActivityId());
            });
        }
        if (!Strings.isNullOrEmpty(sakuraEntryForm.getSignStatus())) {
            lambdaCriteria.eq(q -> {
                q.setSignStatus(sakuraEntryForm.getSignStatus());
            });
        }
        List<SakuraEntryForm> sakuraEntryFormList = lambdaCriteria.orderDesc("id").list(page.getPageCurrent(), page.getPageSize());
        Long count = lambdaCriteria.count();
        page.setList(sakuraEntryFormList);
        page.setTotal(count);
    }

    @Transactional
    @Override
    public void insert(SakuraEntryForm sakuraEntryForm) throws ApiException {
        checkNull(sakuraEntryForm.getActivityId(), "活动id不能为空");
        checkString(sakuraEntryForm.getUserId(), "userId不能为空");
        checkString(sakuraEntryForm.getName(), "姓名不能为空");
        checkString(sakuraEntryForm.getCertificateType(), "证件类型不能为空");
        checkString(sakuraEntryForm.getCertificateCode(), "证件号码不能为空");
        //checkIdCard(sakuraEntryForm.getCertificateCode(), "证件号码有误");
        checkPhone(sakuraEntryForm.getPhone(), "手机号格式有误");
        // checkString(sakuraEntryForm.getArriveTime(), "来校日期不能为空");
        checkNull(sakuraEntryForm.getTakeFamily(), "是否携带家属不能为空");

        String createTime = simpleDateFormat.format(new Date());
        String createTime1 = simpleDateFormat1.format(new Date());
        Activity activity = activityDao.findFirstByActivityIdAndDeleteTag(sakuraEntryForm.getActivityId(), false);
        if (activity.getIsCancel()) {
            errorMsg("活动已取消");
        }
        checkNull(activity, "活动不存在");
        //判断来校日期
     /*   if (sakuraEntryForm.getArriveTime().compareTo(createTime1) < 0) {
            errorMsg("来校日期不能为之前日期");
        }
        if (sakuraEntryForm.getArriveTime().compareTo(activity.getActivityStart().substring(0, 10)) < 0 || sakuraEntryForm.getArriveTime().compareTo(activity.getActivityEnd().substring(0, 10)) > 0) {
            errorMsg("来校日期必须在活动时间内");
        }*/
        //判断是否可以报名
        if (createTime.compareTo(activity.getSignStart()) < 0 || createTime.compareTo(activity.getSignEnd()) > 0) {
            errorMsg("报名已截止");
        }
        if (activity.getActivityPersnNow() >= activity.getActivityPersMax()) {
            errorMsg("报名人数已上限");
        }
        //已报名人数+1
        activity.setActivityPersnNow(activity.getActivityPersnNow() + 1L);
        activityDao.save(activity);
        SakuraEntryForm s = sakuraEntryFormDao.findFirstByUserIdAndSignStatusAndActivityId(sakuraEntryForm.getUserId(), "已报名", sakuraEntryForm.getActivityId());
        if (Objects.nonNull(s)) {
            errorMsg("该用户已经报过名了");
        }
        sakuraEntryForm.setIsChange(false);
        sakuraEntryForm.setCreateTime(createTime);
        sakuraEntryForm.setUpdateTime(createTime);
        if (sakuraEntryForm.getTakeFamily() == true) {
            if (!Strings.isNullOrEmpty(sakuraEntryForm.getFamilyOne())) {
                checkString(sakuraEntryForm.getFamilyOneCode(), "家属1身份证号码不能为空");
            }
            if (!Strings.isNullOrEmpty(sakuraEntryForm.getFamilyTwo())) {
                checkString(sakuraEntryForm.getFamilyTwoCode(), "家属2身份证号码不能为空");
            }
            if (Strings.isNullOrEmpty(sakuraEntryForm.getFamilyOne()) && Strings.isNullOrEmpty(sakuraEntryForm.getFamilyTwo())) {
                errorMsg("家属信息不能为空");
            }
        }
        OapiUserGetResponse userInfoByUserId = dingTalkService.getUserInfoByUserId(sakuraEntryForm.getUserId());
        if (userInfoByUserId.getErrcode().equals(0L)) {
            sakuraEntryForm.setHeadImg(userInfoByUserId.getAvatar());
        } else {
            errorMsg(userInfoByUserId.getErrmsg());
        }

        sakuraEntryForm.setSignStatus("已报名");
        Conversation c = conversationDao.findFirstByActivityIdAndDeleteTag(activity.getActivityId(), false);

        if (activity.getIsDing().equals("是")) {
            updateConversation(sakuraEntryForm, 0L);
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(sakuraEntryForm.getUserId());
        userInfo.setPhone(sakuraEntryForm.getPhone());
        userInfo.setName(sakuraEntryForm.getName());
        userInfo.setCertificateType(sakuraEntryForm.getCertificateType());
        userInfo.setCertificateCode(sakuraEntryForm.getCertificateCode());
        UserInfo byUserId = userInfoService.findByUserId(sakuraEntryForm.getUserId());
        if (Objects.isNull(byUserId)) {
            userInfoService.insert(userInfo);
        } else {
            userInfo.setId(byUserId.getId());
            userInfoService.update(userInfo);
        }
        /**
         * 插入报名记录
         */
        SignRecord firstByActivityIdAndUserId = signRecordDao.findFirstByActivityIdAndUserId(sakuraEntryForm.getActivityId(), sakuraEntryForm.getUserId());
        if (Objects.nonNull(firstByActivityIdAndUserId)) {
            firstByActivityIdAndUserId.setStatus("已报名");
            signRecordDao.save(firstByActivityIdAndUserId);
        } else {
            SignRecord signRecord = new SignRecord();
            signRecord.setStatus("已报名");
            signRecord.setActivityId(sakuraEntryForm.getActivityId());
            signRecord.setUserId(sakuraEntryForm.getUserId());
            signRecordDao.save(signRecord);
        }
        sakuraEntryFormDao.save(sakuraEntryForm);

    }


    @Override
    public void cancel(Long id, String userId) throws ApiException {
        SakuraEntryForm one = sakuraEntryFormDao.findFirstByUserIdAndSignStatusAndActivityId(userId, "已报名", id);
        Activity activity = activityDao.findFirstByActivityIdAndDeleteTag(one.getActivityId(), false);
        activity.setActivityPersnNow(activity.getActivityPersnNow() - 1L);
        checkNull(one, "该用户还未报名");
        if (one.getSignStatus().equals("已取消")) {
            errorMsg("您已取消过了");
        }
        one.setSignStatus("已取消");
        one.setCancelTime(simpleDateFormat.format(new Date()));
        if (activity.getIsDing().equals("是")) {
            updateConversation(one, 1L);
        }
        SignRecord firstByActivityIdAndUserId = signRecordDao.findFirstByActivityIdAndUserId(one.getActivityId(), one.getUserId());
        firstByActivityIdAndUserId.setStatus("已取消");
        signRecordDao.save(firstByActivityIdAndUserId);
        sakuraEntryFormDao.save(one);
        activityDao.save(activity);
    }

    private void updateConversation(SakuraEntryForm sakuraEntryForm, Long status) throws ApiException {
        Conversation c = conversationDao.findFirstByActivityIdAndDeleteTag(sakuraEntryForm.getActivityId(), false);
        checkNull(c, "会话不存在");
        OapiChatUpdateResponse response = new OapiChatUpdateResponse();
        if (status.equals(0L)) {
            response = dingTalkService.updateConversation(c.getChatId(), sakuraEntryForm.getUserId(), "");
        } else if (status.equals(1L)) {
            response = dingTalkService.updateConversation(c.getChatId(), "", sakuraEntryForm.getUserId());
        }
        if (!response.getErrcode().equals(0L)) {
            errorMsg(response.getErrmsg());
        }
    }

    @Override
    public void update(SakuraEntryForm sakuraEntryForm) {
        checkNull(sakuraEntryForm.getActivityId(), "活动id不能为空");
        checkString(sakuraEntryForm.getUserId(), "userId不能为空");
        //checkString(sakuraEntryForm.getName(), "姓名不能为空");
        //checkString(sakuraEntryForm.getCertificateType(), "证件类型不能为空");
        checkString(sakuraEntryForm.getCertificateCode(), "证件号码不能为空");
        //checkIdCard(sakuraEntryForm.getCertificateCode(), "证件号有误");
        //checkPhone(sakuraEntryForm.getPhone(), "手机号格式有误");
        //  checkString(sakuraEntryForm.getArriveTime(), "来校日期不能为空");
        // checkNull(sakuraEntryForm.getTakeFamily(), "是否携带家属不能为空");
        SakuraEntryForm activityId = sakuraEntryFormDao.findFirstByUserIdAndSignStatusAndActivityId(sakuraEntryForm.getUserId(), "已报名", sakuraEntryForm.getActivityId());

      /*  String noUpdate = activityId.getArriveTime() + " 20:00:00";
        long now = new Date().getTime();
        try {
            long time = simpleDateFormat.parse(noUpdate).getTime();
            long before = time - 24 * 60 * 60 * 1000;
            if (now >= before) {
                errorMsg("修改报名时间已过");
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
*/
        Activity activity = activityDao.findFirstByActivityIdAndDeleteTag(sakuraEntryForm.getActivityId(), false);
        checkNull(activity, "活动不存在");
        String createTime = simpleDateFormat.format(new Date());
        if (createTime.compareTo(activity.getSignStart()) < 0 || createTime.compareTo(activity.getSignEnd()) > 0) {
            errorMsg("请在活动时间内修改报名信息");
        }
     /*   String createTime = simpleDateFormat.format(new Date());
        String createTime1 = simpleDateFormat1.format(new Date());
        //判断来校日期
        if (activityId.getArriveTime().compareTo(createTime1) > 0) {
            errorMsg("来校时间不可修改");
        }
        if (sakuraEntryForm.getArriveTime().compareTo(createTime1) < 0) {
            errorMsg("来校日期不能为之前日期");
        }
        if (sakuraEntryForm.getArriveTime().compareTo(activity.getActivityStart().substring(0, 10)) < 0 || sakuraEntryForm.getArriveTime().compareTo(activity.getActivityEnd().substring(0, 10)) > 0) {
            errorMsg("来校日期必须在活动时间内");
        }*/
        //activityId.setName(sakuraEntryForm.getName());
        //    activityId.setArriveTime(sakuraEntryForm.getArriveTime());
        //activityId.setCertificateCode(sakuraEntryForm.getCertificateCode());
        // activityId.setCertificateType(sakuraEntryForm.getCertificateType());
        //activityId.setPhone(sakuraEntryForm.getPhone());
        // activityId.setTakeFamily(sakuraEntryForm.getTakeFamily());
        Boolean isChange = false;
        if (sakuraEntryForm.getTakeFamily() == true) {
            if (!Strings.isNullOrEmpty(sakuraEntryForm.getFamilyOne()) && !("null").equals(sakuraEntryForm.getFamilyOne())) {
                checkString(sakuraEntryForm.getFamilyOneCode(), "家属1证件号码不能为空");
                if (!activityId.getFamilyOneCode().equals(sakuraEntryForm.getFamilyOneCode()) && activityId.getIsChange()) {
                    errorMsg("证件号只能修改一次");
                } else if (!activityId.getFamilyOneCode().equals(sakuraEntryForm.getFamilyOneCode())) {
                    isChange = true;
                }
                List<Object> one = new ArrayList<>();
                for (int i = 0; i < activityId.getFamilyOneCode().length(); i++) {
                    char c = sakuraEntryForm.getFamilyOneCode().charAt(i);
                    char c1 = activityId.getFamilyOneCode().charAt(i);
                    if (c != c1) {
                        one.add(c);
                    }
                }
                if (one.size() > 2) {
                    errorMsg("家属1只能修改证件号2位");
                }
                activityId.setFamilyOneCode(sakuraEntryForm.getFamilyOneCode());
            }
            if (!Strings.isNullOrEmpty(sakuraEntryForm.getFamilyTwo()) && !("null").equals(sakuraEntryForm.getFamilyTwo())) {
                List<Object> two = new ArrayList<>();
                checkString(sakuraEntryForm.getFamilyTwoCode(), "家属2证件号码不能为空");
                if (!activityId.getFamilyTwoCode().equals(sakuraEntryForm.getFamilyTwoCode()) && activityId.getIsChange()) {
                    errorMsg("证件号只能修改一次");
                } else if (!activityId.getFamilyTwoCode().equals(sakuraEntryForm.getFamilyTwoCode())) {
                    isChange = true;
                }
                for (int i = 0; i < activityId.getFamilyTwoCode().length(); i++) {
                    char c = sakuraEntryForm.getFamilyTwoCode().charAt(i);
                    char c1 = activityId.getFamilyTwoCode().charAt(i);
                    if (c != c1) {
                        two.add(c);
                    }
                }
                if (two.size() > 2) {
                    errorMsg("家属2只能修改证件号2位");
                }
                activityId.setFamilyTwoCode(sakuraEntryForm.getFamilyTwoCode());
            }
            if (Strings.isNullOrEmpty(sakuraEntryForm.getFamilyOne()) && Strings.isNullOrEmpty(sakuraEntryForm.getFamilyTwo())) {
                errorMsg("家属信息不能为空");
            }
        }
        if (activityId.getIsChange() && !activityId.getCertificateCode().equals(sakuraEntryForm.getCertificateCode())) {
            errorMsg("证件号只能修改一次");
        } else if (!activityId.getCertificateCode().equals(sakuraEntryForm.getCertificateCode())) {
            isChange = true;
        }
        List<Object> list = new ArrayList<>();
        for (int i = 0; i < activityId.getCertificateCode().length(); i++) {
            char c = sakuraEntryForm.getCertificateCode().charAt(i);
            char c1 = activityId.getCertificateCode().charAt(i);
            if (c != c1) {
                list.add(c);
            }
        }
        if (list.size() > 2) {
            errorMsg("只能修改证件号2位");
        }
        activityId.setIsChange(isChange);
        activityId.setCertificateCode(sakuraEntryForm.getCertificateCode());
        activityId.setUpdateTime(createTime);
        sakuraEntryFormDao.save(activityId);
    }

    @Override
    public SakuraEntryForm findOne(Long activityId, String userId) {
        SakuraEntryForm activityId1 = sakuraEntryFormDao.findFirstByUserIdAndSignStatusAndActivityId(userId, "已报名", activityId);
        checkNull(activityId1, "您还未报名");
        return activityId1;
    }

    @Override
    public JSONObject synchronizationQuery(String startTime, String endTime, String password) {
        checkString(password, "密码不能为空");
        if (!password.equals(DigestUtils.md5Hex("wudaxiaoyouhuodongbiao"))) {
            errorMsg("密码错误");
        }
        LambdaCriteria<SakuraEntryForm> lambdaCriteria = lambdaQuery.create(SakuraEntryForm.class);
        if (StringUtils.isNotBlank(startTime)) {
            lambdaCriteria.gte(q -> {
                q.setUpdateTime(startTime);
            });
        }
        if (StringUtils.isNotBlank(endTime)) {
            lambdaCriteria.lte(q -> {
                q.setUpdateTime(endTime);
            });
        }
        lambdaCriteria.eq(q -> {
            q.setSignStatus("已报名");
        });
        List<SakuraEntryForm> list = lambdaCriteria.list();
        Map<Boolean, String> map = new HashMap<>();
        map.put(true, "是");
        map.put(false, "否");
        JSONObject listJson = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        list.forEach(q -> {
            JSONObject object = new JSONObject();
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("姓名", q.getName());
            jsonObject.put("证件类型", q.getCertificateType());
            jsonObject.put("证件号码", q.getCertificateCode());
            jsonObject.put("手机号", q.getPhone());
            jsonObject.put("是否携带家属", map.get(q.getTakeFamily()));
            if (Objects.isNull(q.getFamilyOne())) {
                jsonObject.put("家属1姓名", "");
                jsonObject.put("家属1证件号码", "");
            } else {
                jsonObject.put("家属1姓名", q.getFamilyOne());
                jsonObject.put("家属1证件号码", q.getFamilyOneCode());
            }
            if (Objects.isNull(q.getFamilyTwo())) {
                jsonObject.put("家属2姓名", "");
                jsonObject.put("家属2证件号码", "");
            } else {
                jsonObject.put("家属2姓名", q.getFamilyTwo());
                jsonObject.put("家属2证件号码", q.getFamilyTwoCode());
            }
            jsonObject.put("备注", "");
            object.put("jsonData", jsonObject);
            jsonArray.add(object);
        });
        listJson.put("list", jsonArray);
        return listJson;
    }

    @Override
    public void insertForm(Long lenth) {
        checkNull(lenth, "长度不能为空");
        String name = "阿阳";
        List<SakuraEntryForm> list = new ArrayList<>();
        for (int i = 0; i < lenth; i++) {
            SakuraEntryForm sakuraEntryForm = new SakuraEntryForm();

            sakuraEntryForm.setSignStatus("已报名");
            sakuraEntryForm.setName(name + i);
            sakuraEntryForm.setCertificateCode(i + "");
            sakuraEntryForm.setCertificateType("身份证");
            sakuraEntryForm.setCreateTime(simpleDateFormat.format(new Date()));
            sakuraEntryForm.setTakeFamily(true);
            sakuraEntryForm.setFamilyOne(i + name);
            sakuraEntryForm.setFamilyOneCode("card" + i);
            sakuraEntryFormDao.save(sakuraEntryForm);
            list.add(sakuraEntryForm);
        }
        sakuraEntryFormDao.save(list);
    }

    @Override
    protected JpaRepository<SakuraEntryForm, Long> getDao() {
        return sakuraEntryFormDao;
    }
}
